﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Transactions;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using DataAccessLayer;

namespace PresentationLayer
{
    public partial class DialogFindAndCombine : Form
    {
        private string tableName;
        private string fieldName;
        private string fieldRefrence;
        private string fieldDescription;
        private string fieldOrder;


        public int fieldFindID { get; set; }
        public int fieldCombineID { get; set; }

        public DialogFindAndCombine(string tableName, string fieldName, string fieldRefrence, string fieldDescription, string fieldOrder, int fieldID)
        {
            InitializeComponent();

            try
            {
                this.tableName = tableName;
                this.fieldName = fieldName;
                this.fieldRefrence = fieldRefrence;
                this.fieldDescription = fieldDescription;
                this.fieldOrder = fieldOrder;

                this.fieldFindID = fieldID;


                DataTable lRec = SQLDatabase.GetDataTable(" SELECT " + this.fieldName + " AS FieldID, " + this.fieldRefrence + " AS FieldRefrence, " + this.fieldDescription + " AS FieldDescription FROM " + this.tableName + (this.tableName.ToUpper() == "ListCustomerName".ToUpper() ? " WHERE DependentOnly = 0 " : "") + " ORDER BY " + this.fieldOrder); //LUU Y: CHI LOAD ListCustomerName: DependentOnly = 0

                if (lRec.Rows.Count > 0)
                {
                    this.comboBoxFindID.DataSource = lRec;
                    this.comboBoxFindID.DisplayMember = "FieldRefrence";
                    this.comboBoxFindID.ValueMember = "FieldID";
                    this.comboBoxFindID.DataBindings.Add("SelectedValue", this, "fieldFindID", true, DataSourceUpdateMode.OnPropertyChanged);

                    this.comboBoxCombineID.DataSource = lRec.Copy();
                    this.comboBoxCombineID.DisplayMember = "FieldRefrence";
                    this.comboBoxCombineID.ValueMember = "FieldID";
                    this.comboBoxCombineID.DataBindings.Add("SelectedValue", this, "fieldCombineID", true, DataSourceUpdateMode.OnPropertyChanged);
                }

                this.checkBoxConfirm.DataBindings.Add("Checked", this.toolStripButtonCombine, "Enabled", true, DataSourceUpdateMode.OnPropertyChanged);

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


        private void comboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                TextBox textBoxDescription;
                if (sender.Equals(this.comboBoxFindID))
                    textBoxDescription = this.textBoxDescriptionFind;
                else
                    textBoxDescription = this.textBoxDescriptionCombine;


                if (((ComboBox)sender).SelectedItem != null)
                {
                    DataRow dataRow = ((DataRowView)((ComboBox)sender).SelectedItem).Row;
                    if (dataRow != null && dataRow["FieldDescription"] != DBNull.Value)
                        textBoxDescription.Text = (string)dataRow["FieldDescription"];
                    else
                        textBoxDescription.Text = "";
                }
                else
                    textBoxDescription.Text = "";
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void toolStripButtonEscapeAndCombine_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender.Equals(this.toolStripButtonCombine))
                {
                    if (this.fieldFindID > 0 && this.fieldCombineID > 0 && this.comboBoxFindID.SelectedItem != null && this.comboBoxCombineID.SelectedItem != null)
                    {
                        if (this.fieldName.ToUpper() == "CommodityID".ToUpper()) //T/H REPLACE COMMDITYID
                        {
                            //KIEM TRA NEU lFieldFindID CO TRONG InventoryDetail => Exit
                            DataTable lRec = SQLDatabase.GetDataTable(" SELECT TOP 1 InventoryDate FROM InventoryMaster INNER JOIN InventoryDetail ON InventoryMaster.InventoryID = InventoryDetail.InventoryID WHERE InventoryDetail.CommodityID = " + this.fieldFindID + " ORDER BY InventoryDate ");
                            if (lRec.Rows.Count > 0) throw new Exception("Can not combine commodity by: " + ((DateTime)lRec.Rows[0]["InventoryDate"]).AddDays(1 - ((DateTime)lRec.Rows[0]["InventoryDate"]).Day).ToShortDateString() + " - " + ((DateTime)lRec.Rows[0]["InventoryDate"]).ToShortDateString() + ".");
                        }

                        if (lReplaceID(this.tableName, this.fieldName, this.fieldFindID, this.fieldCombineID, this.comboBoxCombineID.Text, this.textBoxDescriptionCombine.Text, this.comboBoxFindID.Text, this.textBoxDescriptionFind.Text))
                            this.DialogResult = DialogResult.OK;
                    }
                }

                if (sender.Equals(this.toolStripButtonEscape))
                    this.DialogResult = DialogResult.Cancel;
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        
        private bool lReplaceID(string lTableName, string lFieldName, int lSourceID, int lDestinationID, string lDescription, string lDescriptionOfficial, string lRemarks1, string lRemarks2)
        {
            if (lSourceID == 0 || lDestinationID == 0 || lSourceID == lDestinationID) return false;

            using (TransactionScope transactionScope = new TransactionScope())
            {
                DataTable lRec = SQLDatabase.GetDataTable(" SELECT TableName FROM PublicTableReplace WHERE {fn UCASE(TableReplace)} = N'" + lTableName.ToUpper() + "' ");
                if (lRec.Rows.Count > 0)
                    foreach (DataRow lRecRow in lRec.Rows)
                        SQLDatabase.ExecuteNonQuery("UPDATE " + lRecRow["TableName"] + " SET " + lFieldName + " = " + lDestinationID + " WHERE " + lFieldName + " = " + lSourceID);


                if (lTableName.ToUpper() == "ListCustomerName".ToUpper()) //COMBINE MAPPING
                {
                    SQLDatabase.ExecuteNonQuery("UPDATE ListCustomerName SET DependentOnly = 1 WHERE CustomerID = " + lSourceID); //THANG CHINH CUNG TRO THANH THANG DependentOnly
                    SQLDatabase.ExecuteNonQuery("UPDATE ListCustomerNameColumn SET CustomerID = " + lDestinationID + " WHERE CustomerID = " + lSourceID); //TAT CA DEU MAP VE lDestinationID

                    SQLDatabase.ExecuteNonQuery("DELETE FROM ListCustomerNameColumnFull WHERE CustomerID = " + lSourceID); //REMOVE FOR lSourceID
                    CommonStaticMethod.lSaveCustomerCodeMap(lDestinationID); //REMOVE FOR lDestinationID

                    ////////lRec = SQLDatabase.GetDataTable("SELECT * FROM ListSalesmenCustomer WHERE CustomerID = " + lDestinationID + " ORDER BY SalesmenID");
                    ////////foreach (DataRow lRecRow in lRec.Rows) //XOA TRUNG SALESMEN TREN MOT KHACH HANG: DO 2 KHACH HANG CO CUNG MOT SALESMEN NEN SAU KHI COMBINE SE THANH MOT CUSTOMER CO 2 ROW CUNG 1 SALESMEN
                    ////////    if (lSalesmenID == (int)lRecRow["SalesmenID"])
                    ////////        lRec.Delete;
                    ////////    else
                    ////////        lSalesmenID = (int)lRecRow["SalesmenID"];

                    //COMBINE TENDER DATABASE.BEGIN
                    SQLDatabase.ExecuteNonQuery("UPDATE MainQuotaMaster SET CustomerID = " + lDestinationID + " WHERE CustomerID = " + lSourceID);
                    SQLDatabase.ExecuteNonQuery("UPDATE MainTenderMaster SET CustomerID = " + lDestinationID + " WHERE CustomerID = " + lSourceID);
                    SQLDatabase.ExecuteNonQuery("UPDATE MainTenderDetail SET CustomerID = " + lDestinationID + " WHERE CustomerID = " + lSourceID);
                    //COMBINE TENDER DATABASE.END

                    //If Not lSaveEventLog(ENMVNTaskID.EListCustomerName, lDestinationID, lDescription, lDescriptionOfficial, "[" & lRemarks1 & "] " & lRemarks2, EEventTakenID.ECombine, "Combine " & lRemarks1 & "[" & lSourceID & "] " & lRemarks2 & " With " & lDescription & "[" & lDestinationID & "] " & lDescriptionOfficial) Then GoTo ERR_HANDLER
                }

                transactionScope.Complete();
            }

            CommonStaticMethod.pfCustomerDeleteOrphan(); //DELETE CUSTOMER MO COI

            return true;

        }



    }
}
